package com.example.servlet;

import com.alibaba.fastjson2.JSON;
import com.example.entity.Pet;
import com.example.service.PetService;
import com.example.service.impl.PetServiceImpl;
import com.example.util.AjaxResult;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/savePetServlet")
public class SavePetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String petName = req.getParameter("petName");
        String petBreed = req.getParameter("petBreed");
        String petSex = req.getParameter("petSex");
        String birthday = req.getParameter("birthday");
        String description = req.getParameter("description");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        if(StringUtils.isBlank(petName) || StringUtils.isBlank(petBreed)
                || StringUtils.isBlank(petSex) || StringUtils.isBlank(birthday)
        ){
            pw.print(JSON.toJSONString(AjaxResult.error("必填项信息不全!")));
        } else {
            Pet pet = new Pet();
            pet.setPetName(petName);
            pet.setPetBreed(Byte.parseByte(petBreed));
            pet.setPetSex(Byte.parseByte(petSex));
            pet.setBirthday(birthday);
            pet.setDescription(description);
            PetService petService = new PetServiceImpl();
            int result = petService.save(pet);
            if(result == -1){
                pw.print(JSON.toJSONString(AjaxResult.error("宠物昵称不能重复!")));
            }else if(result > 0){
                pw.print(JSON.toJSONString(AjaxResult.success()));
            }else{
                pw.print(JSON.toJSONString(AjaxResult.error()));
            }
        }
        pw.flush();
        pw.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
